import { login, logout, getInfo } from '@/api/user'
import { role_info } from '@/api/system'

import { getToken, setToken, removeToken, setUserInfo, getUserInfo } from '@/utils/auth'
import { resetRouter } from '@/router'
import NotFound from '@/views/404.vue'
import upath from '../../router/path'

const getDefaultState = () => {
    return {
        token: getToken(),
        nickname: '',
        avatar: '',
        menus: [],
        mainRoutes: {}
    }
}

const state = getDefaultState()

// const getters={

//   getUserInfo:(state)=>{
//     return state.info
//   }
// }

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, nickname) => {
        state.nickname = nickname
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_INFO: (state, menus) => {
        state.menus = menus
    },
    SET_ROUTE: (state, route) => {
        state.mainRoutes = route
    }
}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { adminname, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: adminname.trim(), password: password }).then(response => {
                // console.log(response, 'response')
                commit('SET_TOKEN', response.accessToken)
                setUserInfo(response)
                setToken(response.accessToken)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            let user = getUserInfo()
            let userInfo = JSON.parse(user)
            if (userInfo) {
                role_info({ id: parseInt(userInfo.role_id) }).then(res => {
                    let urlPath = res.paths
                    let newMenus = {}
                    if (userInfo.is_company == 1) {
                        newMenus = JSON.parse(JSON.stringify(upath.menus));
                        let all_menus = {
                            "equipmentlist": [
                                "查看",
                                "增加",
                                "删除",
                                "修改"
                            ],
                            "grouplist": [
                                "查看",
                                "增加",
                                "删除",
                                "修改"
                            ],
                            "inspection": [
                                "查看",
                                "增加",
                                "删除",
                                "修改"
                            ],
                            "playback": [
                                "查看",
                                "增加",
                                "删除",
                                "修改"
                            ],
                            "role": [
                                "查看",
                                "增加",
                                "删除",
                                "修改",
                                "权限"
                            ],
                            "system": [
                                "查看",
                                "增加",
                                "删除",
                                "修改"
                            ],
                            "user": [
                                "查看",
                                "增加",
                                "删除",
                                "修改"
                            ],
                            "warnlist": [
                                "查看",
                                "增加",
                                "删除",
                                "修改"
                            ],
                            "warntype": [
                                "查看",
                                "增加",
                                "删除",
                                "修改"
                            ],
                        }
                        commit('SET_ROUTE', all_menus)
                    } else {
                        newMenus = JSON.parse(JSON.stringify(upath.menus));
                        newMenus.forEach((e, i) => {
                            e.children = e.children.filter(item => (urlPath[item.name] && urlPath[item.name].length != 0))
                            e.children = e.children.filter(item => urlPath[item.name] && (urlPath[item.name][0] == '查看' || urlPath[item.name][1] == '查看' || urlPath[item.name][2] == '查看' || urlPath[item.name][3] == '查看' || urlPath[item.name][4] == '查看'))
                        })
                        commit('SET_ROUTE', res.paths)
                    }
                    let data = { 'nickname': '许广超', 'avatar': 'http://nfqn.soocedu.com/20240312_qn65efb55968886.png', 'menus': newMenus }
                    commit('SET_NAME', data.nickname)
                    commit('SET_AVATAR', data.avatar)
                    commit('SET_INFO', data.menus)
                    resolve(data)
                }).catch(error => {
                    reject(error)
                })
            }
        })
    },
    // get user info
    // getInfo({ commit, state }) {
    //     return new Promise((resolve, reject) => {
    //         getInfo().then(response => {
    //             console.log(response)
    //             const { data } = response
    //             console.log(data)
    //             if (!data) {
    //                 return reject('Verification failed, please Login again.')
    //             }

    //             const { nickname, avatar, menus } = data

    //             // menus.push({path:'/404',component:NotFound,hide:true},{
    //             //   path:'*',
    //             //   redirect:'/404',
    //             //   hidden:'true'
    //             // })

    //             commit('SET_NAME', nickname)
    //             commit('SET_AVATAR', avatar)
    //             commit('SET_INFO', menus)
    //             resolve(data)
    //         }).catch(error => {
    //             reject(error)
    //         })
    //     })
    // },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            // logout(state.token).then(() => {
            commit('SET_TOKEN', '')
            removeToken() // must remove  token  first
            resetRouter()
                // commit('RESET_STATE')
            resolve()
                // }).catch(error => {
                //   reject(error)
                // })
        })
    },



    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
                // commit('RESET_STATE')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    // getters
}